package vn.com.vega.chacha.v2.Asynctask;

import java.lang.ref.WeakReference;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.ActivityBase;
import vn.com.vega.chacha.v2.Appinstant;
import vn.com.vega.chacha.v2.receiver.NetworkStatusReceiver;
import vn.com.vega.music.clientserver.JsonAuth;
import vn.com.vega.music.clientserver.JsonSong;
import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.utils.Const;
import vn.com.vega.music.utils.Util;
import android.os.AsyncTask;

public class AutoLogin extends AsyncTask<Void, Void, Boolean> {
	private static final int AUTHEN_SERVER_ERROR = 0;
	private static final int AUTHEN_FAILED = 1;
	private static final int AUTHEN_SUCCESS = 2;

	private LoginListener mLoginListener;
	WeakReference<ActivityBase> activityRfc;
	private DataStore dataStore;
	private String loginFailMessage;

	public AutoLogin(ActivityBase act, LoginListener listener) {
		mLoginListener = listener;
		activityRfc = new WeakReference<ActivityBase>(act);
		dataStore = DataStore.getInstance();
	}
	
	private boolean checkIsLive() {
		ActivityBase baseAct = activityRfc.get();
		if (baseAct == null || baseAct.isDestroy) {
			return false;
		}
		return true;
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		// TODO Auto-generated method stub
		if (!checkIsLive()) {
			return false;
		}
		ActivityBase act = activityRfc.get();
		if (NetworkStatusReceiver.networkStatus == NetworkStatusReceiver.CONNECTION_TYPE_OFF) {
			loginFailMessage = act.getString(R.string.no_network_connection);
			return false;
		}
		if (AUTHEN_SUCCESS != authenticateApplication()) {
			loginFailMessage = act.getString(R.string.welcome_screen_failed_authenticate);
			return false;
		}
		if (NetworkStatusReceiver.networkStatus == NetworkStatusReceiver.CONNECTION_TYPE_3G) {
			JsonAuth identify = JsonAuth.identify();
			if (identify.isSuccess()) {
				dataStore.setMsisdn(identify.phoneNumber);
				dataStore.setPassword(identify.password);
				dataStore.updateAccountConfig(identify.hashAccount);
				return true;
			} else {
				loginFailMessage = identify.getErrorMessage();
				return false;
			}
		} else {
			String userName = dataStore.getMsisdn();
			String pass = dataStore.getSavedPassword();
			if (Util.checkStringIsemptyOrNull(userName) || Util.checkStringIsemptyOrNull(pass)) {
				loginFailMessage = "";
				return false;
			}
			JsonAuth login = JsonAuth.login(userName, pass);
			if (login.isSuccess()) {
				// Pre load feature song
				Appinstant app = (Appinstant) act.getApplication();
				JsonSong js = JsonSong.loadTopSongList(0);
				if (js.isSuccess()) {
					app.listSongFeature.addAll(js.songs);
				}
				return true;
			} else {
				loginFailMessage = login.getErrorMessage();
				return false;
			}
		}
	}

	@Override
	protected void onPostExecute(Boolean result) {
		// TODO Auto-generated method stub
		if (isCancelled() || !checkIsLive()) {
			return;
		}
//		ActivityBase act = activityRfc.get();
//		Appinstant appinstant = (Appinstant) act.getApplication();
		if (mLoginListener != null) {
			if (result) {
				mLoginListener.loginSuccess();
			} else {
				mLoginListener.loginFail(loginFailMessage);
			}
		}
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		if (checkIsLive()) {
			mLoginListener.startLogin();
		}
	}

	private int authenticateApplication() {

		// Request random key
		JsonAuth ja = JsonAuth.requestAuthKey();

		if (ja.isNetworkError())
			return AUTHEN_SERVER_ERROR;

		if (!ja.isSuccess()) {
			// Service unavailable
			loginFailMessage = ja.getErrorMessage();
			return AUTHEN_FAILED;
		}

		// validate
		JsonAuth validate = JsonAuth.validate(ja.randomKey);

		if (validate.isNetworkError()) {
			return AUTHEN_SERVER_ERROR;
		}

		if (!validate.isSuccess()) {
			// Auth error
			loginFailMessage = validate.getErrorMessage();
			return AUTHEN_FAILED;
		}

		// authen success

		// save extra data here

		dataStore.setConfig(Const.KEY_SMS_SERVER, validate.mService.sms_server);
		dataStore.setConfig(Const.KEY_SMS_CONTENT,
				validate.mService.sms_content);
		dataStore.setConfig(Const.KEY_TRIAL_SMS_CONTENT,
				validate.mService.trial_sms_content);
		dataStore.setConfig(Const.KEY_TRIAL_SMS_SERVER,
				validate.mService.trial_sms_server);

		ActivityBase act = activityRfc.get();
		Util mUtil = new Util(act);
		mUtil.setSharedPre(Const.KEY_SMS_SERVER, validate.mService.sms_server);
		mUtil.setSharedPre(Const.KEY_SMS_CONTENT, validate.mService.sms_content);
		mUtil.setSharedPre(Const.KEY_TRIAL_SMS_SERVER,
				validate.mService.trial_sms_server);
		mUtil.setSharedPre(Const.KEY_TRIAL_SMS_CONTENT,
				validate.mService.trial_sms_content);
		mUtil.setSharedPre(Const.KEY_ASK_RATE,
				Integer.toString(validate.mService.ask_rate));
		// mUtil.setSharedPre(Const.KEY_ASK_RATE, "1");
		mUtil.setSharedPre(Const.KEY_WARNING_MSG,
				validate.mService.warning_message);
		String temp = mUtil.getSharedPre(Const.KEY_LOGIN_COUNT);
		int curr_count = 0;
		try {
			if (temp.trim().equals(""))
				curr_count = 0;
			else
				curr_count = Integer.parseInt(temp);
		} catch (Exception e) {
			// TODO: handle exception
			curr_count = 0;
		}

		mUtil.setSharedPre(Const.KEY_LOGIN_COUNT, "" + (curr_count + 1));
		return AUTHEN_SUCCESS;
	}

	public interface LoginListener {
		public void startLogin();

		public void loginSuccess();

		public void loginFail(String failMessage);
	}

}
